package com.shixi.shixitraining.shixitraining.http;

import android.app.ProgressDialog;
import android.content.Context;
import android.view.Window;

import com.lzy.okgo.callback.AbsCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;

import org.json.JSONObject;

import okhttp3.ResponseBody;

/**
 * Created by jeff on 2017/12/21.
 */

public abstract class DialogStringCallback extends AbsCallback<String> {
    private ProgressDialog dialog;
    private int result_code;
    private String result_message;
    private String responseBody;

    private void initDialog(Context context) {
        dialog = new ProgressDialog(context);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dialog.setMessage("加载中...");
    }

    public DialogStringCallback(Context context) {
        initDialog(context);
    }

    @Override
    public void onStart(Request<String, ? extends Request> request) {
        super.onStart(request);
        if (dialog != null && !dialog.isShowing()) {
            dialog.show();
        }
    }

    @Override
    public void onSuccess(Response<String> response) {
        onParseSuccess(responseBody, result_code, result_message);
    }

    @Override
    public void onFinish() {
        //网络请求结束后关闭对话框
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    @Override
    public String convertResponse(okhttp3.Response response) throws Throwable {
        ResponseBody body = response.body();
        if (body == null) return null;
        responseBody = body.string();
        JSONObject jsonObject = new JSONObject(responseBody);
        result_code = jsonObject.getInt("result_code");
        result_message = jsonObject.getString("result_message");
        return responseBody;
    }

    public abstract void onParseSuccess(String response, int code, String msg);



}
